package com.thinkfit.jy.presenter;

import com.blankj.utilcode.util.ToastUtils;
import com.common.lib.bean.ApplicationBean;
import com.common.lib.bean.SportInfoBean;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.manager.DataManager;
import com.common.lib.mvp.BasePresenter;
import com.common.lib.network.HttpListener;
import com.common.lib.network.HttpMethods;
import com.common.lib.network.HttpObserver;
import com.thinkfit.jy.adapter.DownloadAdapter;
import com.thinkfit.jy.contract.ApplicationContract;
import com.thinkfit.jy.utils.SystemUtils;


import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ApplicationPresenter extends BasePresenter<ApplicationContract.View> implements ApplicationContract.Presenter {

    public ApplicationPresenter(@NotNull ApplicationContract.View rootView) {
        super(rootView);
    }

    @Override
    public void getAdvert() {

    }

    @Override
    public void getVideoList(int type) {

    }


    @Override
    public void getApkList() {
        HttpMethods.Companion.getInstance().getApkList(
                new HttpObserver(false, getRootView(), new HttpListener<ArrayList<ApplicationBean>>() {
                    @Override
                    public void onSuccess(@Nullable ArrayList<ApplicationBean> list) {
                        if (getRootView() == null) {
                            return;
                        }
                        getRootView().getApkListSuccess(list);
                    }

                    @Override
                    public void dataError(@Nullable int code, @Nullable String msg) {
                        if (getRootView() == null) {
                            return;
                        }
                        System.out.println("ddddddddddddddddddddddd   getVersion 222");
                        getRootView().showErrorDialog(code, msg);
                    }

                    @Override
                    public void connectError(@Nullable Throwable e) {
                        if (getRootView() == null) {
                            return;
                        }
                        getRootView().showErrorDialog(-1, "");
                    }
                }, getCompositeDisposable()));
    }

    @Override
    public void getSportInfo() {
        HttpMethods.Companion.getInstance().getSportInfo(
                DataManager.Companion.getInstance().getMyInfo().getUid(),
                new HttpObserver(false, getRootView(), new HttpListener<SportInfoBean>() {
                    @Override
                    public void onSuccess(@Nullable SportInfoBean bean) {
                        if (getRootView() == null) {
                            return;
                        }
                        getRootView().getSportInfoSuccess(bean);
                    }

                    @Override
                    public void dataError(@Nullable int code, @Nullable String msg) {
                        if (getRootView() == null) {
                            return;
                        }
                    }

                    @Override
                    public void connectError(@Nullable Throwable e) {
                        if (getRootView() == null) {
                            return;
                        }
                    }
                }, getCompositeDisposable()));
    }
    Disposable installDisposable, deviceCommondDispose,delQueryInstallDispose,deleyTime,silentUninstallDisposable,silentUninstallAppDisposable;
    ConcurrentHashMap<String, DownloadAdapter.DownloadData> installMap = new ConcurrentHashMap<>();
    ConcurrentHashMap<String, Boolean> installedMap = new ConcurrentHashMap<>();
    ConcurrentHashMap<String, Boolean> refreshMap = new ConcurrentHashMap<>();
    ConcurrentHashMap<String, Boolean> silentUninstallMap = new ConcurrentHashMap<>();
    String installKey = "";
    boolean isInstall = false;
    DownloadAdapter.DownloadData installValue = null;
    public void install(DownloadAdapter.DownloadData downloadData){
//        AppInstallTask.Builder builder = new AppInstallTask.Builder();
//        builder.addInstallation(new AppInstallTask.Installation(
//                downloadData.packageName,
//                downloadData.versionCode,
//                downloadData.url,
//                downloadData.downloadPath,
//                downloadData.downloadFileName
//        ));
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   packageName : "+downloadData.packageName);
        synchronized (installMap){
            if(!installMap.containsKey(downloadData.packageName)){
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   packageName : "+downloadData.packageName);
                installMap.put(downloadData.packageName, downloadData);
            }
            if(!installedMap.containsKey(downloadData.packageName)){
                installedMap.put(downloadData.packageName, false);
            }
        }

//        if(delQueryInstallDispose != null&&!installDisposable.isDisposed() ){
//            return;
//        }

        String packageName = downloadData.packageName;
//        ToastUtils.showShort("开始安装 :" + packageName);
        installNotify();

//        Observable.interval(1000, TimeUnit.MILLISECONDS)
//                .subscribeOn(Schedulers.newThread())
//                .subscribe(new Observer<Long>() {
//                    @Override
//                    public void onSubscribe(Disposable disposable) {
//                        delQueryInstallDispose = disposable;
//                    }
//
//                    @Override
//                    public void onNext(Long aLong) {
//                        installNotify();
////                                    SystemOperateUtil.getInstance().getSystemOperate().silentInstall(installation.getLocal());
////                            System.out.println("dddddddddddddddddddd  开始安装 :"+installation.getPackageName());
//
//                    }
//                    @Override
//                    public void onError(Throwable throwable) {
//
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });

    }

    public void installNotify() {
        if (isInstall) {
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  installNotify 有安装正在进行");
            return;
        }
        installValue = null;
        installKey = "";
        synchronized (installMap){
            for (String key : installMap.keySet()) {
                installKey = key;
                installValue = installMap.get(key);
                break;
            }
            if (installValue != null) {
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa installNotify : " + installValue.name + "：" + installValue.packageName);
//                addInstallView(StringUtils.isEmpty(installValue.getAppName()) ? installValue.getPackageName() : installValue.getAppName());
            }
        }
        SystemUtils.getInstance().installApk(getRootView().getAppContext(),
                new File(installValue.downloadPath+ installValue.downloadFileName));
        isInstall = true;
        installMap.remove(installValue.packageName);
//        Observable.create(new ObservableOnSubscribe<String>() {
//                    @Override
//                    public void subscribe(ObservableEmitter<String> emitter) throws Exception {
//                        try {
//                            if(installValue != null){
//                                System.out.println( "aaaaaaaaaaaaaaaaaaaaaaaaa installNotify 开始安装" + installKey);
//                                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   安装路径 :"+ installValue.downloadPath+ installValue.downloadFileName);
//                                AppCommHelper mAppCommHelper = new AppCommHelper();
//                                boolean install = mAppCommHelper.silentInstallApp(installValue.downloadPath+ installValue.downloadFileName);
////                                SystemOperateUtil.getInstance().getSystemOperate().silentInstall(installValue.getDownloadPath());
////                                SystemOperateUtil.getInstance().getSystemOperate().installAppC(installValue);
//                                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   安装结果 :"+install);
//                                if(install){
//                                    if(!emitter.isDisposed()){
//                                        emitter.onNext(installKey);
//                                    }
//                                }else {
//                                    System.out.println( "aaaaaaaaaaaaaaaaaaaaaaaaa installNotify 开始安装" + installKey + "异常");
//                                    disposeInstall();
//                                }
//                            }
//
//                        }catch (Exception e){
//                            e.printStackTrace();
//                            System.out.println( "aaaaaaaaaaaaaaaaaaaaaaaaa installNotify 开始安装" + installKey + "异常");
//                            disposeInstall();
//                        }
//                    }
//                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<String>() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//                        installDisposable = d;
//                    }
//
//                    @Override
//                    public void onNext(String aBoolean) {
//                        getRootView().installOver(aBoolean);
//                        installMap.remove(aBoolean);
//                        installedMap.remove(aBoolean);
//                        refreshMap.put(aBoolean,true);
//                        ToastUtils.showShort(aBoolean + "安装完成");
//                        System.out.println(  "aaaaaaaaaaaaaaaaaaaaaaaaa installNotify " + aBoolean + "安装完成");
//                        deleyTime();
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        disposeInstall();
//                    }
//
//                    @Override
//                    public void onComplete() {
//                        disposeInstall();
//                    }
//                });
    }

    public void installOver(String packageName){
        synchronized(installMap){
            installMap.remove(packageName);
            installedMap.remove(packageName);
            refreshMap.put(packageName,true);
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa      installMap.size : "+installMap.size());
            if(installMap.size() > 0){
                installNotify();
            }
        }

    }

    public void setIsInstall(boolean b){
        isInstall = b;
    }


    public void deleyTime(){
        if (deleyTime != null && !deleyTime.isDisposed()) {
//            LogUtils.l(mRootView.getContext(), "installNotify 有安装正在进行");
            return;
        }
        String refreshKey = "";
        if(refreshMap.size() > 0){
            for (String key : refreshMap.keySet()) {
                refreshKey = key;
                break;
            }
        }
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  refreshKey : "+refreshKey);
        String finalRefreshKey = refreshKey;
        Observable.interval(4000,TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.newThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        deleyTime = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        DownloadAdapter downloadAdapter = getRootView().getDownloadAdapter();
                        if(getRootView().getDownloadAdapter() != null){
                            int packagePosition = downloadAdapter.getPackagePosition(finalRefreshKey);
                            DownloadAdapter.DownloadData downloadData = downloadAdapter.getData().get(packagePosition);
                            int version = SystemUtils.getVersion(getRootView().getAppContext(), finalRefreshKey);
                            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  version : "+version);
                            if(version >0){
//                                    if(ConfigUtils.getVersion(mRootView.getContext(),finalRefreshKey) >= downloadData.versionCode){
//                                        refresh(finalRefreshKey);
//                                    }
                                refresh(finalRefreshKey);
//                                System.out.println("dddddddddddddddddddddddddd  isFinalRefreshKey : "+(finalRefreshKey.equals("com.degal.scienceteminal")));
//                                if(finalRefreshKey.equals("com.degal.scienceteminal")){
//                                    EventBusUtil.postMessage("",EventBusTags.IS_INTEGRATE);
//                                }
                                disposeVersion();
                                disposeInstall();
                            }

                        }
//                        if(aLong<=5){
//
//                        }else {
//                            disposeVersion();
//                            disposeInstall();
//                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disposeVersion();
                        disposeInstall();
                    }

                    @Override
                    public void onComplete() {
                        disposeVersion();
                        disposeInstall();
                    }
                });
    }

    public void refresh(String packageName){
        HashMap<String,String> map = new HashMap<>();
        map.put(EventBusEvent.REFRESH_VERSION,packageName);
        EventBus.getDefault().post(map);
        getRootView().refreshVersion(packageName);
        refreshMap.remove(packageName);
        disposeVersion();
    }

    private void disposeVersion(){
        if(deleyTime != null && !deleyTime.isDisposed()){
            deleyTime.dispose();
        }
        if(installMap.size() > 0){
            installNotify();
        }else{
            if (delQueryInstallDispose != null && !delQueryInstallDispose.isDisposed()) {
                delQueryInstallDispose.dispose();
                delQueryInstallDispose=null;
            }
            ToastUtils.showShort("下载安装流程结束");
//            EventBusUtil.postMessage("",EventBusTags.XHL_OVER);
        }
//        if(refreshMap.size() > 0){
//            deleyTime();
//        }
    }

    private void disposeInstall(){
        installKey = "";
        installValue = null;
        if(installDisposable != null && !installDisposable.isDisposed()){
            installDisposable.dispose();
            installDisposable=null;
//            removeInstallVIew();
        }
        if(installMap.size() > 0){
            installNotify();
        }else{
            if (delQueryInstallDispose != null && !delQueryInstallDispose.isDisposed()) {
                delQueryInstallDispose.dispose();
                delQueryInstallDispose=null;
            }
            ToastUtils.showShort("下载安装流程结束");
//            EventBusUtil.postMessage("",EventBusTags.XHL_OVER);
        }
    }
}
